
import java.net.MalformedURLException;
import java.net.URL;
import java.sql.*;   // methods to process SQL commands
import java.util.ArrayList;
import java.util.Collections;

import javax.imageio.ImageIO;
import javax.sql.*;  // ditto
//import org.postgresql.jdbc3.Jdbc3PoolingDataSource; // connection via JDBC to postgrSQL
import java.awt.Image;
import java.awt.Toolkit;
import java.io.IOException;   // enable IOException objects & handling
import java.io.PrintWriter;   // enable PrintWriter (so can use .println())
import javax.servlet.http.*;  // provides servlet functionality
import javax.servlet.*;	      // ditto
import javax.*;


import java.awt.event.*;
import java.awt.image.BufferedImage;
import java.awt.image.ImageObserver;
import java.util.Locale;


public class SingleMovieTitle extends HttpServlet
{
	//private static DataSource ds;	// contains DB and connection data; see init()
	private static Connection connection;
	//private static StringBuffer buf;
	
	
	public static String issueQuery(String movieId)
    {	
		
		String temp = "";
		int year = 0;
		String director = " ";
		String trailer = " ";
	
		
		// see the API doc at java.sun.com for details
		try
		{
			Statement select = connection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);
			ResultSet result = select.executeQuery("Select * from movies where id = " + movieId);
			
			if(result.next())
			{
				//movieTitle = result.getString(2);
				year = result.getInt(3);
				director = result.getString(7) + " " + result.getString(4);
				//banner = result.getString(5);
				trailer = result.getString(6);
				
			}
			//making table
			temp += "<div><TABLE bgcolor=\"#FFFFFF\" border=0 bordercolorlight=\"#C0C0C0\" bordercolordark=\"#808080\">";
			temp += "<TR valign=top>";
			temp += "<TD width=310 height=53><div class=\"wpmd\">";
			temp += "<div align=right><B><U><BR></U></B></div>";
			temp += "<div align=right><B><U>Release Year:</U></B></div>";
			temp += "</div>";
			temp += "</TD>";
			temp += "<TD width=395 height=53><div class=\"wpmd\">";
			temp += "<div><BR></div>";
			
			temp += "<div>" + year + "</div>";
			
			temp += "</div>";
			temp += "</TD>";
			temp += "</TR>";
			temp += "<TR valign=top>";
			temp += "<TD width=99 height=52><div class=\"wpmd\">";
			temp += "<div align=right><B><U><BR></U></B></div>";
			temp += "<div align=right><B><U>Director:</U></B></div>";
			temp += "</div>";
			temp += "</TD>";
			temp += "<TD width=395 height=52><div class=\"wpmd\">";
			temp += "<div><BR></div>";
			
			temp += "<div>" + director + "</div>";
			temp += "</div>";
			temp += "</TD>";
			temp += "</TR>";
			
			temp += "<TR valign=top>";
			temp += "<TD width=99 height=55><div class=\"wpmd\">";
			temp += "<div align=right><B><U><BR></U></B></div>";
			temp += "<div align=right><B><U>Starring:</U></B></div>";
			temp += "</div>";
			temp += "</TD>";
			temp += "<TD width=395 height=55><div class=\"wpmd\">";
			temp += "<div><BR></div>";
			
			String stars = findStars(movieId);
			//movie stars in movie
			temp += "<div> " + stars + "</div>";
			temp += "</div>";
			temp += "</TD>";
			temp += "</TR>";
			
			temp += "<TR valign=top>";
			temp += "<TD width=99 height=60><div class=\"wpmd\">";
			temp += "<div align=right><B><U><BR></U></B></div>";
			temp += "<div align=right><B><U>Genre(s):</U></B></div>";
			temp += "</div>";
			temp += "</TD>";
			temp += "<TD width=395 height=60><div class=\"wpmd\">";
			temp += "<div><BR></div>";
			
			String genresTemp = findGenres(movieId);
			temp += "<div>" + genresTemp + "</div>";
			temp += "</div>";
			temp += "</TD>";
			temp += "</TR>";
			

			temp += "<TR valign=top>";
			temp += "<TD width=99 height=55><div class=\"wpmd\">";
			temp += "<div align=right><B><U><BR></U></B></div>";
			temp += "<div align=right><B><U>Trailer:</U></B></div>";
			temp += "</div>";
			temp += "</TD>";
			temp += "<TD width=395 height=55><div class=\"wpmd\">";
			temp += "<div><BR></div>";
			temp += "<div> <a href=\" " + trailer + "\" title=\"Watch trailer now\"> Watch trailer now! </a></div>";
			temp += "</div>";
			temp += "</TD>";
			temp += "</TR>";
			
			temp += "</TABLE>";
			temp += "</div>";	
		
		}
		catch (SQLException sqle)
		{
			temp.concat("SQL exception occured: " + sqle.getMessage());
		}		
		
		// return buffered string of text
	
		return temp;
	}
	
	public static String findGenres(String movieId) throws SQLException
	{
		Statement select4 = connection.createStatement();
		ResultSet resultGenresID = select4.executeQuery("Select genre_id from genres_in_movies where movie_id = " + movieId);
		String temp = "";
		while(resultGenresID.next())
		{
			Statement select5 = connection.createStatement();
			ResultSet resultGenres = select5.executeQuery("Select * from genres where id = " + resultGenresID.getInt(1));
			if(resultGenres.next())
				temp += resultGenres.getString(2) + " <br>";
		}
		if(temp.equals(""))
			return "No genres";
		return temp;	
	}
	public static String findStars(String movieId) throws SQLException
	{
		Statement select2 = connection.createStatement();
		ResultSet resultStarsID = select2.executeQuery("Select star_id from stars_in_movies where movie_id = " + movieId);
		String temp = "";
		
		while(resultStarsID.next())
		{
			Statement select3 = connection.createStatement();
			ResultSet resultStars = select3.executeQuery("Select * from stars where id = " + resultStarsID.getInt(1));
			if(resultStars.next())
			{
				temp += "<a href=\"SingleStarPage?id=" + resultStars.getInt(1) + "\"> " + resultStars.getString(2) + " " + resultStars.getString(3) + " </a><br>";				
			}
		}
	
		if(temp.equals(""))
			return "No movie stars";
		return temp;
	}
	public void doGet(HttpServletRequest request, HttpServletResponse response)
		throws IOException, ServletException
	{
		if (!Bridge.hasBeenToMainPage(request.getSession(), response.getWriter()))
		{
			return;
		}
		
		response.setContentType("text/html");
		PrintWriter out = response.getWriter();
		String movieId = request.getParameter("id");
		StringBuffer buf = new StringBuffer();
		String movieTitle = " ";
		String banner = " ";
		try 
		{
			Class.forName("org.postgresql.Driver").newInstance();
			connection = DriverManager.getConnection(
					"jdbc:postgresql://localhost/fabflixs", "testuser", "testpass");
			
			if(movieId == null)
			{
				buf.append("No movie was chosen");
			}
			else
			{
				
				Statement select2 = connection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);
				ResultSet result2 = select2.executeQuery("Select * from movies where id = " + movieId);
				
				if(result2.next())
				{
					movieTitle = result2.getString(2);
					banner = result2.getString(5);
				}
				//creating form
				buf.append("<form name=\"movieForm\" action=\"DvdProcessor\" method=\"POST\">");
				//out.println("<div align=\"left\"><br>");
				
				//making main table
				buf.append("<div><TABLE bgcolor=\"#FFFFFF\" border=5 bordercolorlight=\"#C0C0C0\" bordercolordark=\"#808080\">");
				buf.append("<TR valign=top>");
				buf.append("<TD colspan=2 height=39><div class=\"wpmd\">");
				buf.append("<div align=center><font size=32px\">" + movieTitle.toUpperCase() + "</font></div>");
				buf.append("</div>");
				buf.append("</TD>");
				buf.append("</TR>");
				  
				//banner
				buf.append("<TR valign=top>");
				buf.append("<TD valign=top align=center width=448 height=238><BR>");
				
				int width = 0;
				//buf.append("Banner URL: " + banner + "<br><br>");
				
				String imageType = banner;
				if (banner.length() >= 4)
					imageType = banner.substring(banner.length()-4, banner.length());
				
				//buf.append("image type extension: " + imageType + "<br><br>");
				if(imageType.equalsIgnoreCase("bmp") || imageType.equalsIgnoreCase("jpg") || imageType.equalsIgnoreCase("png"))
				{
					buf.append("<a href=\"" + banner+ "\">");
					buf.append("<img style=\" margin:0px auto 10px; text-align:center;cursor:hand;width:" + width+ "px;\" src=\""+banner+"\" border=\"0\" alt=\""+movieTitle+"\" /></a>");
				}
				else
				{
					try
					{
						BufferedImage image = ImageIO.read(new URL(banner));
						width = image.getWidth();
						
						//ImageSize size = new ImageSize(new URL(banner));
						//width = size.getWidth();
						//int height = size.getHeight();
						//buf.append("WIDTH OF IMAGE: " + width + "<br><br>");
						if(width > 448)
						{
							int widthPercentage = (448 / width ) * 100;
					  
							width = width*widthPercentage;
					
						}
						if(width > 0)
						{
							buf.append("<a href=\"" + banner+ "\">");
							buf.append("<img style=\" margin:0px auto 10px; text-align:center;cursor:hand;width:" + width+ "px;\" src=\""+banner+"\" border=\"0\" alt=\"\" /></a>");
						}
						else
						{
							width = 200;
							banner = "../images/kirbynoposter.jpg";
							buf.append("<img style=\" margin:0px auto 10px; text-align:center;cursor:hand;width:" + width+ "px;\" src=\""+banner+"\" border=\"0\" alt=\"No poster available\" /></a>");
	
						}
						
							
					}
					catch(MalformedURLException e)
					{
						width = 200;
						banner = "../images/kirbynoposter.jpg";
						buf.append("<img style=\" margin:0px auto 10px; text-align:center;cursor:hand;width:" + width+ "px;\" src=\""+banner+"\" border=\"0\" alt=\"\" /></a>");
	
					}
					catch(IllegalArgumentException e)
					{
						width = 200;
						banner = "../images/kirbynoposter.jpg";
						buf.append("<img style=\" margin:0px auto 10px; text-align:center;cursor:hand;width:" + width+ "px;\" src=\""+banner+"\" border=\"0\" alt=\"\" /></a>");
	
					}
					catch(IOException e)
					{
						width = 200;
						banner = "../images/kirbynoposter.jpg";
						buf.append("<img style=\" margin:0px auto 10px; text-align:center;cursor:hand;width:" + width+ "px;\" src=\""+banner+"\" border=\"0\" alt=\"\" /></a>");
	
					}
					catch (Exception e)
					{
						width = 200;
						banner = "../images/kirbynoposter.jpg";
						buf.append("<img style=\" margin:0px auto 10px; text-align:center;cursor:hand;width:" + width+ "px;\" src=\""+banner+"\" border=\"0\" alt=\"\" /></a>");
	
					}
				}
				buf.append("</TD>");
				
				//buf.append("Banner URL: " + banner + "<br><br>");
				buf.append("<TD rowspan=2 width=495><BR>");
				
				//making inner table that holds movie data
				buf.append(issueQuery(movieId));
		
				buf.append("</TD>");
				buf.append("</TR>");
				buf.append("<TR valign=top>");
				buf.append("<TD width=448 ><BR>");
				
				buf.append("<div align=center><a href=\"./DvdProcessor?movieId=" + movieId + "\"><IMG border=0 src=\"../images/AddToCart.png\"></a></div>");
				buf.append("<br>");
				buf.append("</div>");
	
				buf.append("</TD>");
				buf.append("</TR>");
				
				
				buf.append("</TABLE>");
				buf.append("</div>");
			
		
				buf.append("</form>");
			}
			out.println(Template.getTemplateHTML("Single Movie Page", buf.toString(), Constants.straightToCart,
					request.getSession() ));
			connection.close();
		}
		catch (SQLException sqle)
		{
			buf.append("SQL exception occured");
		}	
		catch (ClassNotFoundException cnfe)
		{
			buf.append("ClassNotFound exception occured");
		}
		catch (InstantiationException ie)
		{
			buf.append("Instantiation exception occured");
		}
		catch (IllegalAccessException iae)
		{
			buf.append("IllegalAccess exception occured");
		}
	
	}
	
	// Upon init of servlet, open the moviedb database
	public void init() 
	{
		/*
		try
		{
		// connect to DB
		Class.forName("org.postgresql.Driver").newInstance();
		connection = DriverManager.getConnection(
				"jdbc:postgresql://localhost/fabflixs", "testuser", "testpass");
		buf = new StringBuffer();	// StringBuffer is faster than String
		}
		catch (SQLException sqle)
		{
			buf.append("SQL exception occured");
		}	
		catch (ClassNotFoundException cnfe)
		{
			buf.append("ClassNotFound exception occured");
		}
		catch (InstantiationException ie)
		{
			buf.append("Instantiation exception occured");
		}
		catch (IllegalAccessException iae)
		{
			buf.append("IllegalAccess exception occured");
		}*/
	}

	
}


